﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;

namespace SisocanaFronEnd.Services
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "SaveFileService" in code, svc and config file together.
    public class SaveFileService : ISaveFileService
    {
        public FileInfo[] getFiles(string directoryPath)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, directoryPath);
            if (!Directory.Exists(path))
                return new FileInfo[0];
            DirectoryInfo folder = new DirectoryInfo(path);
            return folder.GetFiles();
        }

        public bool deleteFile(string filePath)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
            try
            {
                if (!File.Exists(path))
                    return false;

                File.Delete(path);
                return true;
            }
            catch(Exception){
                return false;
            }            
        }

        public bool saveFile(string filePath, byte[] fileContent, bool compressed)
        {
            try
            {
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
                string directoryName = Path.GetDirectoryName(path);
                if (!Directory.Exists(directoryName))
                    Directory.CreateDirectory(directoryName);

                File.WriteAllBytes(path, fileContent);

                if (compressed)
                {
                    using(FileStream file = new FileStream(path, FileMode.Open)){
                        ZipFile zipFile = new ZipFile(file);
                        foreach (ZipEntry zipEntry in zipFile)
	                    {
			                if (!zipEntry.IsFile) continue;
			            
                            String entryFileName = Path.GetFileName(zipEntry.Name);			            
                            byte[] buffer = new byte[4096];
			                Stream zipStream = zipFile.GetInputStream(zipEntry);
                            String fullZipToPath = Path.Combine(directoryName, entryFileName);
                            using (FileStream streamWriter = File.Create(fullZipToPath)) {
				                StreamUtils.Copy(zipStream, streamWriter, buffer);
			                }
		                }
                        zipFile.Close();
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
